package cn.laixueit.service.impl;

import cn.laixueit.mapper.BrandMapper;
import cn.laixueit.pojo.Brand;
import cn.laixueit.pojo.Goods;
import cn.laixueit.result.PageResult;
import cn.laixueit.service.BrandService;
import cn.laixueit.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    private BrandMapper brandMapper;

    @Override
    public PageResult<Brand> page(String key, Integer page, Integer rows, String sortBy, Boolean desc) {
        Page<Brand> p = new Page<>(page, rows);
        IPage<Brand> brandIPage = page(p, getWrapper(key, sortBy, desc));
        PageResult<Brand> result = new PageResult<>();
        result.setTotalPage(brandIPage.getPages());
        result.setTotal(brandIPage.getTotal());
        result.setItems(brandIPage.getRecords());
        return result;
    }

    @Override
    @Transactional
    public void saveBrandAndCategory(Brand brand,Long[] cids) {
        save(brand);
        for (Long cid :cids) {
            brandMapper.saveBrandAndCategory(cid,brand.getId());
        }
    }

    @Override
    public List<Brand> brandListByCid(Long cid) {
        return brandMapper.brandListByCid(cid);
    }

    @Override
    public List<Brand> findBrandList(List<Long> bids) {
        List<Brand> brandList = listByIds(bids).stream().collect(Collectors.toList());
        return brandList;
    }

    private Wrapper<Brand> getWrapper(String key, String sortBy, Boolean desc) {
        QueryWrapper<Brand> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(key)){
            wrapper.like("name",key);
        }
        if(StringUtils.isNotBlank(sortBy)){
            wrapper.orderBy(true,desc,sortBy);
        }
        return wrapper;
    }
}
